package staff

import (
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/gjwt"
	"duoke/utils/gmd5"
	"duoke/utils/orm"
	"duoke/utils/response"
	"duoke/utils/valid"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

var Staff = new(staffCtl)

type staffCtl struct{}

// 账户登录
func (ctl *staffCtl) Login(c *gin.Context) {
	var req model.ReqStaffLogin
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	// 系统登录
	staff, err := service.Staff.Login(req.Username, req.Password)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 生成token
	token, err := gjwt.Build(gjwt.Data{Uid: staff.UserId, Role: "staff", Acid: staff.Acid, GoodsId: staff.GoodsId}, 3600*24*30)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "登录成功", gin.H{"token": token})
}

// 账户信息
func (ctl *staffCtl) Info(c *gin.Context) {
	staffR, _ := service.Request.Staff(c)
	staff := new(tables.GoodsUser)
	has, err := orm.Db.Where("goods_id =? AND user_id =?", staffR.GoodsId, staffR.Id).Get(staff)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "该账户不存在", nil)
		return
	}
	// 默认头像
	if staff.Avatar == "" {
		staff.Avatar = "https://himg.bdimg.com/sys/portrait/hotitem/wildkid/47"
	}
	response.Success(c, "", gin.H{"id": staff.Id, "nickname": staff.Nickname, "avatar": staff.Avatar, "phone": staff.Phone, "password": ""})
}

// 账户更新
func (ctl *staffCtl) Update(c *gin.Context) {
	staffR, _ := service.Request.Staff(c)
	var req model.ReqStaff
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	staff := new(tables.GoodsUser)
	has, err := orm.Db.Where("goods_id =? AND user_id =?", staffR.GoodsId, staffR.Id).Get(staff)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "该账户不存在", nil)
		return
	}
	// 密码加密
	if req.Password != "" {
		staff.Password, _ = gmd5.Encrypt(req.Password)
	}
	_, err = orm.Db.ID(staff.Id).Cols("name", "avatar", "phone", "nickname", "password").Update(staff)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "保存成功", nil)
}
